﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Services.Client;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using DevComponents.WPF.Controls;
using ZhiHeng.Consume.DataContract;
using ZhiHeng.OneCard.CommUtility;
using ZhiHeng.OneCard.WpfClient.Common;
using ZhiHeng.OneCard.WpfClient.Model;
using ZhiHeng.OneCard.WpfClient.ViewModel;

namespace ZhiHeng.OneCard.WpfClient.Forms
{
    /// <summary>
    /// LoginControl.xaml 的交互逻辑
    /// </summary>
    public partial class LoginControl : UserControl
    {
        public LoginControl()
        {
            InitializeComponent();
           
        }

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Enter();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MsgGrid.Visibility = Visibility.Visible;

        }

        private void ButtonOK_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
            System.Environment.Exit(System.Environment.ExitCode);

        }

        private RectangleGeometry rg;
        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            rg = new RectangleGeometry(new Rect(new Point(0, 0), BoxGrid.RenderSize));
            BoxGrid.Clip = rg;
            RectAnimation ra = new RectAnimation();
            ra.Duration = TimeSpan.FromMilliseconds(500);
            ra.To = new Rect(0, BoxGrid.ActualHeight / 2, BoxGrid.ActualWidth, 0);
            ra.FillBehavior = FillBehavior.HoldEnd;
            rg.BeginAnimation(RectangleGeometry.RectProperty, ra);
            Timer t = new Timer(new TimerCallback(ReBack));
            t.Change(500, 0);
        }

        void ReBack(object o)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new System.Windows.Forms.MethodInvoker(
                delegate()
                {
                    MsgGrid.Visibility=Visibility.Collapsed;
                }));
        }

        private void pass_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Enter();
            }
            else if (e.Key == Key.Tab)
            {
                e.Handled = true;
                txt_Id.Focus();
            }
        }
        //登录事件
        void Enter()
        {
            InputGrid.Visibility = Visibility.Collapsed;
            ProgressControl1.Visibility = Visibility.Visible;


            string[] para = new string[] { txt_Id.Text, txt_pass.Password };
            Thread t = new Thread(Start);
            t.Start(para);

        }

        //验证线程
        void Start(object parameter)
        {
            //Thread.Sleep(1000);
            string[] para = parameter as string[];
            bool IsSucceed = false;
            string AnimationName = "LabelAnimation";
            string Labelstr = "";

            try
            {
                var a = new @operator().ExtGetSingle(" it.OperCode == @OperCode", true,
                                                     new SearchParameter("OperCode", para[0]));
                if (a != null)
                {
                    if (a.OperPIN == para[1])
                    {
                        ViewModelBase.UserInfo = a;
                        MainViewModel.Instance.Userinfo = a;
                        IsSucceed = true;
                    }
                    else
                    {

                        Labelstr = "密码错误！";
                    }
                }
                else
                {
                    Labelstr = "此用户不存在！";
                }
            }catch(Exception e)
            {
                Labelstr = "服务器验证失败！";
            }

            if (IsSucceed)
            {
                AnimationName = "OkAnimation";
            }
            else
            {
                AnimationName = "LabelAnimation";
            }

            if (!System.Windows.Application.Current.Dispatcher.CheckAccess())
            {
                System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new System.Windows.Forms.MethodInvoker(
                delegate()
                {
                    BeginAnimation(IsSucceed, AnimationName, Labelstr);
                }));
            }else
            {
                BeginAnimation(IsSucceed, AnimationName, Labelstr);
            }

        }
        /// <summary>
        /// 验证完成更改界面
        /// </summary>
        /// <param name="IsSucceed"></param>
        /// <param name="AnimationName"></param>
        /// <param name="Labelstr"></param>
        void BeginAnimation(bool IsSucceed, string AnimationName, string Labelstr)
        {

            if (IsSucceed)
            {
                this.Visibility = Visibility.Hidden;
                txt_Id.Text = "";
                txt_pass.Password = "";
                label1.Content = "";
                LoginStatus = true;
                
            }
            else
            {
                label1.Content = Labelstr;
                LoginStatus = false;
                txt_pass.Focus();
                Storyboard OkAnimation = FindResource(AnimationName) as Storyboard;
                OkAnimation.FillBehavior = FillBehavior.HoldEnd;
                OkAnimation.Begin();
            }

        }

        private void Close_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            MsgGrid.Visibility = Visibility.Visible;
            try
            {
                //rg.BeginAnimation(RectangleGeometry.RectProperty, null);
                BoxGrid.Clip = null;
            }
            catch
            {
            }
        }

        private void txt_Id_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key==Key.Enter)
            txt_pass.Focus();
        }

        /// <summary>
        /// 登录状态
        /// </summary>
        [Description("登录状态")]
        public bool LoginStatus
        {
            get { return (bool)GetValue(LoginStatusProperty); }
            set
            {
                SetValue(LoginStatusProperty, value);
                if (value)
                {

                }
                else
                {
                    InputGrid.Visibility = Visibility.Visible;
                    ProgressControl1.Visibility = Visibility.Collapsed;
                }
            }
        }

        // Using a DependencyProperty as the backing store for IsOut.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LoginStatusProperty =
            DependencyProperty.Register("LoginStatus", typeof(bool), typeof(LoginControl), new UIPropertyMetadata(false));




        /// <summary>
        /// 利用反射赋值
        /// </summary>
        /// <param name="source">源数据</param>
        /// <param name="target">目标数据，不能为Null</param>
        private static void RefGetValue(object source, object target)
        {
            if (source != null)
            {

                Type t = source.GetType();
                PropertyInfo[] pi = t.GetProperties();
                foreach (PropertyInfo p in pi)
                {
                    try
                    {
                        PropertyInfo pii = source.GetProperty(p.Name);
                        pii.SetValue(target, p.GetValue(source, null), null);
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            if(e.MouseDevice.Target is Grid)
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                (this.GetVisualRoot() as Window).DragMove();
            }
        }

        private void LoginGrid_Loaded(object sender, RoutedEventArgs e)
        {
            txt_Id.Focus();
        }
    }
}
